<script lang="tsx" setup>
import { reactive, ref, watch } from 'vue';
import Empty from './empty.vue';
import 'vue-cropper/dist/index.css';
// eslint-disable-next-line import/order
import { VueCropper } from 'vue-cropper';
import { useAuthStore } from '@/store/modules/auth';
import { uploadAvatar } from '@/service/api/system/user';
defineOptions({
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Cropper'
});
const visible = defineModel<boolean>('visible', {
  default: false
});
interface Options {
  img: string | any; // 裁剪图片的地址
  autoCrop: boolean; // 是否默认生成截图框
  autoCropWidth: number; // 默认生成截图框宽度
  autoCropHeight: number; // 默认生成截图框高度
  fixedBox?: boolean; // 固定截图框大小 不允许改变
  fileName: string;
  previews: any; // 预览数据
  outputType: string;
  visible: boolean;
}

const authStore = useAuthStore();
interface Props {
  imageUrl: string;
}
const props = withDefaults(defineProps<Props>(), {});

const urlRef = ref<string>();
const cropper = ref<any>(null);
/** 向左旋转 */
const rotateLeft = () => {
  cropper.value.rotateLeft();
};
/** 向右旋转 */
const rotateRight = () => {
  cropper.value.rotateRight();
};
/** 图片缩放 */
const changeScale = (num: number) => {
  cropper.value.changeScale(num || 1);
};
// 图片裁剪数据
const options = reactive<Options>({
  img: '',
  autoCrop: true,
  autoCropWidth: 200,
  autoCropHeight: 200,
  // fixedBox: true,
  outputType: 'jpg',
  fileName: '',
  previews: {},
  visible: false
});
const loading = ref(false);
watch(visible, () => {
  if (visible.value) {
    options.img = props.imageUrl;
    console.log(options.img);
  }
});
const beforeUpload = (data: any) => {
  const { file } = data;
  // 校验文件类型
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    (window as any).$message.error('Only image files are allowed!');
    return false; // 阻止上传
  }
  // 校验文件大小（例如限制为5MB）
  const maxSize = 5 * 1024 * 1024;
  if (file.size > maxSize) {
    (window as any).$message.error('File size cannot exceed 5MB!');
    return false; // 阻止上传
  }
  // const reader = new FileReader();
  // reader.onload = e => {
  //   const url = window.URL.createObjectURL(new Blob([e?.target?.result as string])); // 将图像 URL 赋值给裁剪组件
  //   options.img = url;
  //   options.fileName = file.file.name;
  // };
  // reader.readAsDataURL(file.file);
  const reader = new FileReader();
  reader.readAsDataURL(file.file);
  reader.onload = () => {
    options.img = reader.result;
    options.fileName = file.file.name;
  };
  return true; // 允许上传
};
const generateFileName = (extension = 'png') => {
  const timestamp = Date.now(); // 当前时间戳
  const randomNum = Math.floor(Math.random() * 10000); // 随机数
  return `file_${timestamp}_${randomNum}.${extension}`; // 生成文件名
};
const handleClose = () => {
  visible.value = false;
};
interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();
const handleCrop = async () => {
  cropper.value.getCropBlob(async (img: any) => {
    console.log('img', img);
    loading.value = true;
    const formData = new FormData();
    const file = new File([img], generateFileName(), { type: img.type });
    formData.append('avatarfile', file);
    const { data, error } = await uploadAvatar(formData);
    loading.value = false;

    if (!error) {
      (window as any).$message.success(data?.msg);
      handleClose();
      await authStore.featchUserInfo();
      emit('submitted');
    }
  });
};
</script>

<template>
  <NModal v-model:show="visible" title="图片裁剪" preset="card" class="w-400px">
    <div class="flex flex-col flex-gap-20px">
      <div class="h-300px">
        <VueCropper
          ref="cropper"
          :img="options.img"
          :info="true"
          :auto-crop="options.autoCrop"
          :auto-crop-width="options.autoCropWidth"
          :auto-crop-height="options.autoCropHeight"
          :fixed-box="options.fixedBox"
          :output-type="options.outputType"
        />
      </div>
      <div>
        <NSpace justify="space-around">
          <NSpace>
            <NTooltip trigger="hover">
              <template #trigger>
                <NUpload :show-file-list="false" accept="image/*" :default-upload="false" @before-upload="beforeUpload">
                  <NButton>
                    <template #icon>
                      <SvgIcon icon="hugeicons:cursor-rectangle-selection-02" />
                    </template>
                  </NButton>
                </NUpload>
              </template>
              选择文件
            </NTooltip>
            <NTooltip trigger="hover">
              <template #trigger>
                <NButton @click="rotateLeft">
                  <template #icon>
                    <SvgIcon icon="material-symbols-light:rotate-90-degrees-ccw-outline-rounded" />
                  </template>
                </NButton>
              </template>
              左旋转
            </NTooltip>
            <NTooltip trigger="hover">
              <template #trigger>
                <NButton @click="rotateRight">
                  <template #icon>
                    <SvgIcon icon="material-symbols-light:rotate-90-degrees-cw-outline-rounded" />
                  </template>
                </NButton>
              </template>
              右旋转
            </NTooltip>
            <NTooltip trigger="hover">
              <template #trigger>
                <NButton @click="changeScale(1)">
                  <template #icon>
                    <SvgIcon icon="ep:zoom-in" />
                  </template>
                </NButton>
              </template>
              放大
            </NTooltip>
            <NTooltip trigger="hover">
              <template #trigger>
                <NButton @click="changeScale(-1)">
                  <template #icon>
                    <SvgIcon icon="ep:zoom-out" />
                  </template>
                </NButton>
              </template>
              缩小
            </NTooltip>
            <!--
 <NTooltip trigger="hover">
              <template #trigger>
                <NButton @click="preview">
                  <template #icon>
                    <SvgIcon icon="material-symbols:eye-tracking-outline-sharp" />
                  </template>
                </NButton>
              </template>
              预览
            </NTooltip>
-->
          </NSpace>
        </NSpace>
      </div>
    </div>
    <template #footer>
      <NSpace justify="end">
        <NButton @click="handleClose">取消</NButton>
        <NButton :loading="loading" type="primary" @click="handleCrop">保存</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style lang="scss" scoped>
.header_bg {
  width: 100%;
  background: url('@/assets/svg-icon/avatar_bg.svg') no-repeat;
}

.avatar-container {
  position: relative;
  display: inline-block;
}

// .avatar-image {
//   border-radius: 50%;
// }

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 70px;
  height: 70px;
  background-color: rgba(0, 0, 0, 0.6);
  /* 半透明遮罩 */
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  /* 平滑过渡 */
}

.avatar-container:hover .overlay {
  opacity: 1;
  /* 悬浮时显示遮罩 */
}
.avatar-upload-preview {
  position: absolute;
  top: 50%;
  transform: translate(50%, -50%);
  width: 200px;
  height: 200px;
  border-radius: 50%;
  box-shadow: 0 0 4px #ccc;
  overflow: hidden;
}
</style>
